package nacos

import (
	"errors"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/common/logger"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"mgs/config"
	"mgs/toolkit"
	"strconv"
)

func Register(cfg config.Config) {
	var nc = cfg.Nacos
	if len(nc.ServiceName) == 0 {
		logger.Info("Nacos is not registered. Registration needs to start serviceName")
		return
	}
	clientConfig := constant.ClientConfig{
		NotLoadCacheAtStart: true,
		LogDir:              nc.LogDir,
		CacheDir:            nc.CacheDir,
	}
	if nc.TimeoutMs > 0 {
		clientConfig.TimeoutMs = nc.TimeoutMs
	}
	if len(nc.LogLevel) > 0 {
		clientConfig.LogLevel = nc.LogLevel
	}
	if len(nc.LogDir) == 0 {
		clientConfig.LogDir = "./logs"
	}
	if len(nc.CacheDir) == 0 {
		clientConfig.CacheDir = "./logs"
	}

	// 服务配置
	var scArr = nc.ServerConfigs
	var serverConfigs []constant.ServerConfig
	for _, sc := range scArr {
		serverConfig := constant.ServerConfig{
			Scheme:      sc.Scheme,
			ContextPath: sc.ContextPath,
			IpAddr:      sc.IpAddr,
			Port:        sc.Port,
		}
		serverConfigs = append(serverConfigs, serverConfig)
	}
	client, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	var ip = nc.ClientIp
	if len(ip) == 0 {
		// 当前服务器 IP 地址
		externalIp, _ := toolkit.ExternalIP()
		ip = externalIp.String()
	}

	// 注册实例配置
	_port, _ := strconv.Atoi(cfg.System.Port)
	instance := vo.RegisterInstanceParam{
		Ip:          ip,
		Port:        uint64(_port),
		Enable:      true,
		Healthy:     true,
		ServiceName: nc.ServiceName,
		Ephemeral:   true,
	}
	if nc.Weight == 0 {
		instance.Weight = 10
	} else {
		instance.Weight = nc.Weight
	}
	if len(nc.ClusterName) > 0 {
		instance.ClusterName = nc.ClusterName
	}
	if len(nc.GroupName) > 0 {
		instance.GroupName = nc.GroupName
	}
	ok, err := client.RegisterInstance(instance)
	if !ok {
		logger.Error("注册本服务发生错误, " + err.Error())
		panic(errors.New("注册本服务发生错误"))
	}
}
